package com.zhang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.jdbc.StringUtils;
import com.zhang.mapper.IOutputInfoMapper;
import com.zhang.mapper.IOutputOrderMapper;
import com.zhang.pojo.OutputCarBean;
import com.zhang.pojo.OutputInfoBean;
import com.zhang.pojo.OutputOrderBean;
import com.zhang.service.IOutputInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 出库信息详情业务接口
 */
@Service
@Transactional
public class OutputInfoServiceImpl implements IOutputInfoService {

    @Autowired
    private IOutputInfoMapper outputInfoMapper;
    @Autowired
    private IOutputOrderMapper outputOrderMapper;

    @Override
    public IPage<OutputInfoBean> findByPageAndItem(Page<OutputInfoBean> page, String name, LocalDate start, LocalDate end) {
        UpdateWrapper<OutputInfoBean> wrapper = new UpdateWrapper<>();
        if (!StringUtils.isNullOrEmpty(name)){
            wrapper.like("oi_name",name);
        }if (start != null){
            wrapper.ge("oi_time",start);
        }if (end != null){
            wrapper.le("oi_time",end);
        }
        return outputInfoMapper.selectPage(page,wrapper);
    }

    @Override
    public void add(OutputInfoBean outputInfoBean, List<OutputCarBean> outputCarBeans) {
        outputInfoMapper.insert(outputInfoBean);

        System.out.println(outputInfoBean.getId());

        List<OutputOrderBean> list = new ArrayList<>();
        for (OutputCarBean outputCarBean : outputCarBeans) {
            OutputOrderBean orderBean = new OutputOrderBean();
            orderBean.setName(outputCarBean.getName());
             orderBean.setMill(outputCarBean.getMill());
             orderBean.setMoney(outputCarBean.getSale());
             orderBean.setCount(outputCarBean.getCount());
             orderBean.setTypeId(outputCarBean.getTypeId());
             orderBean.setOutputInfoId(outputInfoBean.getId());
             list.add(orderBean);
        }

        for (int j = 0; j < list.size(); j++) {
            outputOrderMapper.insert(list.get(j));
        }
    }

    @Override
    public OutputInfoBean findByid(int id) {
//        OutputInfoAndOrder a = new OutputInfoAndOrder();
//        a.setOutputInfoBean();

        OutputInfoBean outputInfoBean = outputInfoMapper.selectById(id);
        QueryWrapper<OutputOrderBean> wrapper = new QueryWrapper<>();
        wrapper.eq("fk_outputInfoId",id);
        outputInfoBean.setOutputOrderBeans(outputOrderMapper.selectList(wrapper));
//
//        a.setOutputOrderBean();
        return outputInfoBean;
    }
}
